import '@/js/common/filter.js'
import instance from '@/api/index.js'
import pagination from '@/components/common/pageComponent'
import {print} from '@/js/util';
import baseURL from '@/js/common/baseURL'
import { Loading } from 'element-ui';
export default {
  name: "OrderList",
  data() {
    return {
      dialogVisibleSuccess:false,
      exportNo:'',
      faildetailOut:[],
      dialogVisibleFaill:false,
      fileList:[],
      dialogVisibleSynchronous:false,
      dialogVisibleChose:false,
      dialogVisible:false,
      cancelOrderParam: {
        orderId: '', //取消订单和确认发货id
        remark: ''
      },
      sku: "",
      retreatingType: [], //退补类型
      replaceIndex: '', //更换商品时替换的索引
      operationType: '',//页面标识 1确认订单 2配货页面
      orderDetail: {},//订单详情
      showFlag: false,//禁止修改样式
      modalTitle: "",//modal标签
      countryOptions: [],//国家选项
      foreachIndex: 0,
      checkedProduct: [],//跟换产品checkbox
      selectedChannel: null,
      currentPage: 1,
      toPage: "1",
      itemTem: {},
      orderList: [],//订单列表
      orderStatus: new Map(),//订单状态
      orderType: new Map(),//订单状态
      platformStatus: new Map(),//平台状态
      conditions: {
        orderId: null,
        orderEndTime: '',
        orderStartTime: '',
        storeId:''
      },//查询条件
      channelCount: new Map(),//渠道汇总信息
      statusBtns: [
        {
          "statusCode": "All",
          "statusValue": "0",
          "statusName": "全部",
          "cssName": "primary"
        },
        {
          "statusCode": "UnConfirmed",
          "statusValue": "1",
          "statusName": "待确认",
          "cssName": "warning"
        },
        {
          "statusCode": "PendingDeliver",
          "statusValue": "2",
          "statusName": "待发货",
          "cssName": "warning"
        },
        {
          "statusCode": "Prepare",
          "statusValue": "3",
          "statusName": "配货中",
          "cssName": "success"
        },
        {
          "statusCode": "Canceled",
          "statusValue": "4",
          "statusName": "已取消",
          "cssName": "success"
        },
        {
          "statusCode": "Deliver",
          "statusValue": "5",
          "statusName": "已发货",
          "cssName": "info"

        }
      ],
      orderConfirmParam: {
        logistics: '',
        orderId: '',
        billCode: '',
        orderType: '0'
      },//确认订单提交
      addProductList: [],//获取更换产品列表
      addClass: -1,//平台下标
      shopClass: -1,//店铺账号下标
      countOrderClass: 0, //订单统计下标
      platformChannelsBtns: [],//平台渠道
      shopListBtn: [],
      pages: {
        total: 0,
        current: 1,
        display: 10,
      },
      inventory: {
        total: 0,
        pageNum: 1,
        dispaly: 5
      },
      logisticsList: [],//获取物流渠道列表
      select:'1',
      selectInputValue:'',
      orderTime:[],//订单日期
      searchPopChannel:null,//弹框渠道搜索
      searchPopShop:null,//弹框店铺搜索
      searchPopTimeList:[],
      searchPopTableList:[],//9610表格数据
      searchPopshopListBtn:[],//店铺list
      showTableList:[],
      popCurrentPage:1,
      popTotalCount:null,
      searchPopPlatformOrderId:'',
      innerVisible:false,
      customsNo:'',//报关区号
      synchronousChannel: null,
      synchronousshopListBtn:[],
      synchronousshopValue:'',
      synchronousTimeList:[],
      successCount:'',
      errorCount:'',
      dialogVisibleFaillSecond:false,
      failMessage:'',
      failIndex:1,
      loadingInstance:null,
      showFaildetailOut:[],
      logisticsListA:[],
      totalNumPage:0,
      orderForm: {
        orderType: 1
      },
      importUrl: '/api/v1/common/order/import/1'
    }
  },
  components: {
    pagination
  },
  methods: {
    handleProgress(){
      this.loadingInstance = this.$loading({
        lock: true,
        background: 'rgba(0, 0, 0, 0.7)'
      });
    },
    handleSuccessFile(res){
      if (res.success) {
        if ( res.data.errorCount == 0) {
          this.dialogVisibleSuccess = true;
          this.fileList = []
        }else {
          this.faildetailOut = res.data.errorMap;
          this.showFaildetailOut =  this.faildetailOut.slice((this.failIndex-1)*10,this.failIndex*10);
          this.failIndex=1;
          this.dialogVisibleFaill = true;
          this.exportNo= res.data.exportNo
          this.fileList = []
          this.successCount = res.data.success
          this.errorCount = res.data.errorCount
        }
      }else {
         this.dialogVisibleFaillSecond = true;
         this.failMessage = res.msg;
        this.fileList = []
      }
      this.loadingInstance.close()
    },
    failPopPageChange(index){
      this.failIndex = index;
      this.showFaildetailOut = this.faildetailOut.slice((index - 1)*10,index*10);
    },
    handleErro(res){
      this.loadingInstance.close()
      this.$message({
        showClose: false,
        message: `${res.data.message},上传失败!`,
        type: 'error'
      });
      this.fileList = []
    },
    downLoadFail(){
      let param = {exportNo:this.exportNo}
      let api = `/v1/common/orderError/download?exportNo=${this.exportNo}`
      instance({
        method: 'post',
        url: api,
        data: param,
        responseType: 'blob'
      }).then( (data)=> {
        if (data) {
          this.downloadFile(data,'订单信息')
        }else {

        }

      })
    },
    //消息提示
    alertMessage: function (value) {
      if (value) {
        this.$message({
          showClose: false,
          message: '操作成功!',
          type: 'success'
        });
      } else {
        this.$message({
          showClose: false,
          message: '操作失败!',
          type: 'error'
        });
      }
    },
    //清除sku
    clearParam: function () {
      let vm = this;
      vm.sku = '';
      vm.cancelOrderParam = {};
    },
    //清除订单列表查询条件
    clearCondtionParam: function () {
      let vm = this;
      vm.conditions.status != 0;
      vm.selectedChannel = null;
      vm.addClass = -1;
      vm.shopClass = -1;
      vm.conditions.storeId = '';
      vm.conditions.orderId = '';
      this.shopListBtn = [];
      this.orderTime = [];
      this.selectInputValue = ''
      vm.getOrderList();

    },
    //分页
    pagechange: function (currentPage) {
      this.currentPage = currentPage;
      this.getOrderList();
    },
    pagechange1: function (currentPage) {
      this.inventory.pageNum = currentPage;
      this.addProduct();
    },
    getCountryOptions: function () {
      let vm = this;
      instance({
        method: 'POST',
        url: '/v1/ebay/meta/country/getList'
      }).then(function (data) {
        if (data.data.success) {
          vm.countryOptions = data.data.data;
          console.log("afterCountry=" + vm.orderDetail);
        } else {
          vm.$message({
            showClose: false,
            message: '系统问题，请稍后再试!',
            type: 'error'
          });
        }
      })
    },
    //配货
    editOutGoods: function (id, view) { //view 是操作标识
      let vm = this;
      vm.modalTitle = "发货确认"; //模态框title
      vm.showFlag = true;
      vm.operationType = view;
      vm.getOrderDetail(id);
    },
    //取消订单给把订单号取出
    orderCancel: function (id) {
      let vm = this;
      vm.cancelOrderParam.orderId = id;
    },
    //取消订单数据提交
    cancelOrderSubmit: function () {
      let vm = this;
      instance({
        method: 'post',
        data: vm.cancelOrderParam,
        url: '/v1/order/cancel'
      }).then(function (data) {
        vm.cancelOrderParam.remark = '';
        if (data.data.success) {
          $('#modal-order-cancel').modal('hide');
        }
        vm.alertMessage(data.data.success);
        vm.getOrderList();
      });

    },
    //确认订单
    confirmOrder: function (id, view) {
      let vm = this;
      vm.modalTitle = "确认订单";//模态框title
      vm.showFlag = true;
      vm.operationType = view;
      vm.getOrderDetail(id);
    },

    //查看订单详情
    viewOrderDetail: function (id) {
      this.$router.push(`/v1/order/detail?orderId=${id}`)
    /*  let vm = this;
      vm.showFlag = false;
      vm.modalTitle = "订单详情"; //模态框title
      vm.getOrderDetail(id);*/
    },
    //获取订单详情
    getOrderDetail: function (id) {
      let vm = this;
      vm.foreachIndex = 0;
      instance({
        method: 'get',
        url: '/v1/order/get/' + id
      }).then(function (data) {
        if (data.data.success) {
          vm.orderDetail = data.data.data;
          if (vm.orderDetail) {
            vm.getWarehouseStockBySku(vm.orderDetail.items[vm.foreachIndex].factSku);
          }
        } else {
          vm.$message({
            showClose: false,
            message: '系统问题，请稍后再试!',
            type: 'error'
          });
        }
      })
      // alert(JSON.stringify(vm.orderDetail));
    },

    //根据sku获取仓库，库存下拉框
    getWarehouseStockBySku: function (_sku) {
      let vm = this;
      instance({
        method: 'post',
        url: '/v1/warehouse/getGoodsStockInfoList',
        data: {
          sku: _sku
        }
      }).then(function (data) {
        if (data.data.data == null) {
          vm.$alert('此商品没有维护库存，请维护相关商品库存！', '提示', {
            confirmButtonText: '确定',
          });
        }
        let wareHouseMap = new Map();
        let wareHouseMapValue = {};
        if (vm.orderDetail.items[vm.foreachIndex]) {
          if (data.data.data != null) {
            for (let i = 0; i < data.data.data[0].stockInfoVOS.length; i++) {
              //将仓库ID作为key值，存入map中
              if (wareHouseMap.has(data.data.data[0].stockInfoVOS[i].whId)) {
                //先判断有没有此仓库ID，如果有，则做库存累加；
                wareHouseMapValue = wareHouseMap.get(data.data.data[0].stockInfoVOS[i].whId);
                wareHouseMapValue.stockQty = parseInt(wareHouseMapValue.stockQty) + parseInt(data.data.data[0].stockInfoVOS[i].stockQty);
                wareHouseMap.set(data.data.data[0].stockInfoVOS[i].whId, wareHouseMapValue);
              } else {
                let currentWareHouseMapValue = {};
                currentWareHouseMapValue.whName = data.data.data[0].stockInfoVOS[i].whName;
                currentWareHouseMapValue.stockQty = data.data.data[0].stockInfoVOS[i].stockQty;
                currentWareHouseMapValue.goodsId = data.data.data[0].goodsId;
                wareHouseMap.set(data.data.data[0].stockInfoVOS[i].whId, currentWareHouseMapValue);
              }
              // wareHouseMap.set(data.data.data[0].stockInfoVOS[i].whId, wareHouseMapValue);
            }
          }
          vm.orderDetail.items[vm.foreachIndex].wareHouseOptions = [];
          let currentItem = vm.orderDetail.items[vm.foreachIndex];
          wareHouseMap.forEach((value, key) => {
            let wareHouseOption = {};
            wareHouseOption.whId = key;
            wareHouseOption.whName = value.whName;
            wareHouseOption.stockQty = value.stockQty;
            currentItem.goodsId = value.goodsId;
            currentItem.wareHouseOptions.push(wareHouseOption);
          });
          vm.$set(vm.orderDetail.items, vm.foreachIndex, currentItem);
          vm.foreachIndex++;
          if (vm.orderDetail.items[vm.foreachIndex]) {
            vm.getWarehouseStockBySku(vm.orderDetail.items[vm.foreachIndex].factSku);
          } else {
            console.log("afterPush=" + vm.orderDetail);
          }
        } else {

        }
      })
    },
    //发货和确认订单数据提交
    commit: function (id) {
      let vm = this;
      let postUrl = ''
      //需要做校验
      let orderInfo = {};
      if (!vm.orderDetail.phone) {
        vm.$alert('请输入联系方式！', '提示', {
          confirmButtonText: '确定',
        });
        return;
      }
      orderInfo.phone = vm.orderDetail.phone;// 联系电话
      orderInfo.postalCode = vm.orderDetail.postalCode;// 邮编
      if (!vm.orderDetail.country) {
        vm.$alert('请选择国家！', '提示', {
          confirmButtonText: '确定',
        });
        return;
      }
      orderInfo.country = vm.orderDetail.country;// 国家
      orderInfo.countryName = vm.orderDetail.countryName;// 国家名
      if (!vm.orderDetail.state) {
        vm.$alert('请输入省区州！', '提示', {
          confirmButtonText: '确定',
        });
        return;
      }
      orderInfo.state = vm.orderDetail.state;// 省/州
      if (!vm.orderDetail.city) {
        vm.$alert('请输入城市区！', '提示', {
          confirmButtonText: '确定',
        });
        return;
      }
      orderInfo.city = vm.orderDetail.city;// 城市
      if (!vm.orderDetail.street1) {
        vm.$alert('请详细地址！', '提示', {
          confirmButtonText: '确定',
        });
        return;
      }
      orderInfo.street1 = vm.orderDetail.street1;// 联系地址1
      orderInfo.street2 = vm.orderDetail.street2;// 联系地址2
      if (!vm.orderDetail.buyerId) {
        vm.$alert('请输入买家id！', '提示', {
          confirmButtonText: '确定',
        });
        return;
      }
      orderInfo.buyerId = vm.orderDetail.buyerId;// 买家id
      if (!vm.orderDetail.name) {
        vm.$alert('请输入买家名字！', '提示', {
          confirmButtonText: '确定',
        });
        return;
      }
      orderInfo.name = vm.orderDetail.name;// 买家名
      if (!vm.orderDetail.items || vm.orderDetail.items.length == 0) {
        vm.$alert('请选择订单商品！', '提示', {
          confirmButtonText: '确定',
        });
        return;
      }
      orderInfo.items = [];
      for (let i = 0; i < vm.orderDetail.items.length; i++) {
        let goods = vm.orderDetail.items[i];
        let item = {};
        if (!goods.price) {
          vm.$alert('请输入商品单价！', '提示', {
            confirmButtonText: '确定',
          });
          return;
        }
        item.price = goods.price;
        if (!goods.sku) {
          vm.$alert('请选择商品！', '提示', {
            confirmButtonText: '确定',
          });
          return;
        }
        item.sku = goods.sku;
        item.goodsId = goods.goodsId;
        item.factGoodsId = goods.factGoodsId;
        if (!goods.quantity) {
          vm.$alert('请输入发货数量！', '提示', {
            confirmButtonText: '确定',
          });
          return;
        }
        item.quantity = goods.quantity;
        if (!goods.stockId) {
          vm.$alert('请选择发货仓库！', '提示', {
            confirmButtonText: '确定',
          });
          return;
        }
        item.stockId = goods.stockId;
        item.itemId = goods.itemId;
        orderInfo.items.push(item);
      }
      //数据精简
      if (vm.operationType == '1') {
        //订单确认
        postUrl = '/v1/order/confirm/' + id;
      } else if (vm.operationType == '2') {
        //配货
        postUrl = '/v1/order/prepare/' + id;
      }
      orderInfo.shipping = vm.orderDetail.shipping || 0;// 邮资
      orderInfo.mail = vm.orderDetail.mail;// 邮箱
      orderInfo.total = vm.orderDetail.total;// 订单金额
      orderInfo.platformFee = vm.orderDetail.platformFee;// 平台服务费
      orderInfo.transferFee = vm.orderDetail.transferFee;// 转账费
      orderInfo.account = vm.orderDetail.account;// 收款账户
      orderInfo.payTimeStr = vm.orderDetail.payTimeStr;// 收款时间
      orderInfo.treatType = vm.orderDetail.treatType;// 退补类型
      orderInfo.treatMoney = vm.orderDetail.treatMoney;// 退补金额
      orderInfo.remark = vm.orderDetail.remark;// 备注
      orderInfo.otherPhone = vm.orderDetail.otherPhone;// 联系电话2
      orderInfo.mail = vm.orderDetail.mail;// 邮箱
      orderInfo.houseNumber = vm.orderDetail.houseNumber;// 门牌号
      orderInfo.message = vm.orderDetail.message;// 平台留言

      instance({
        method: 'post',
        url: postUrl,
        data: orderInfo
      }).then(function (data) {
        if (data.data.success) {
          $('#modal-order-confirm').modal('hide');
        }
        vm.alertMessage(data.data.success);
        vm.getOrderList();
      });
    },

    platformChannels: function (index) {
      let vm = this;
      if ( vm.selectedChannel == 0){
        vm.selectedChannel = null;
      }

      vm.shopListBtn = [];
      vm.shopListBtn.push({id:null,name:'全部'})
      this.conditions.storeId = null;
      instance({
        method: 'post',
        url: 'v1/author/getAuthorShopList',
        data: {
          id: vm.selectedChannel
        }
      }).then(function (data) {
        if (data.data.success) {
          let result = data.data.data;
          vm.shopListBtn = vm.shopListBtn.concat(result);
          if ( vm.selectedChannel == null){
            vm.selectedChannel = 0;
          }
        }
        // vm.getOrderList();
        // vm.getChannelCount();
      })
    },

    //获取平台列表
    getPlatform: function () {
      let vm = this;
      vm.platformChannelsBtns = [];
      vm.platformChannelsBtns.push({id:0,platformName:'全部'})
      instance({
        method: 'post',
        url: '/v1/author/getPlatFrom'
      }).then(function (data) {
        if (data.data.success) {
          let result = data.data.data;
          vm.platformChannelsBtns = vm.platformChannelsBtns.concat(result);
        }
      })
    },

    //获取店铺账号列表
    getShopList: function () {
      let vm = this;
      var id = null;
      if (vm.selectedChannel) {
        id = vm.selectedChannel;
      }
      vm.conditions.status = 0;
      instance({
        method: 'post',
        url: 'v1/author/getAuthorShopList',
        data: {
          id: id
        }
      }).then(function (data) {
        if (data.data.success) {
          vm.shopListBtn = data.data.data;
        }
      })
    },

    //店铺账号
    shopChannels: function (_index) {
      let vm = this;
      vm.shopClass = _index;
      if (-1 == _index) {
        vm.conditions.storeId = null;
      } else {
        vm.conditions.storeId = vm.shopListBtn[_index].id;
      }
      // vm.getOrderList();
      // vm.getChannelCount();
    },

    //获取物流渠道列表
    //确认发货页面
    confirmOutGoods: function (id) {
      let vm = this;
      vm.orderConfirmParam.orderId = id;
      instance({
        method: 'get',
        url: '/v1/dict/logistics'
      }).then(function (data) {
        if (data.data.success) {
          vm.logisticsList = data.data.data;
        }
      })
    },
    //确认发货提交
    okOutGoods: function () {
      let vm = this;
      if (!vm.orderConfirmParam.orderId) {
        vm.$alert('系统异常，请刷新！', '提示', {
          confirmButtonText: '确定',
        });
        return;
      }
      // if (!vm.orderConfirmParam.billCode) {
      //   vm.$alert('请输入运单号！', '提示', {
      //     confirmButtonText: '确定',
      //   });
      //   return;
      // }
      // if (!vm.orderConfirmParam.logistics) {
      //   vm.$alert('请选择物流渠道！', '提示', {
      //     confirmButtonText: '确定',
      //   });
      //   return;
      // }
      instance({
        method: 'post',
        url: '/v1/order/logistics/bind',
        data: vm.orderConfirmParam
      }).then(function (data) {
        if (data.data.success) {
          $('#modal-Delivery').modal('hide');
        }
        vm.alertMessage(data.data.success);
        vm.getOrderList();
      })
    },
    //获取渠道汇总信息
    getChannelCount: function () {
      let vm = this;
      if (vm.selectedChannel == null){
        vm.selectedChannel = 0
      }
      let url = 'v1/order/' + vm.selectedChannel + '/count?';
      url = '/v1/order/count/get'
   /*   if (vm.conditions) {
        if (vm.conditions.storeId) {
          url = url + 'storeId=' + vm.conditions.storeId;
        }
        if (vm.conditions.orderStartTime) {
          url = url + "&begin=" + vm.conditions.orderStartTime + "&";
        }
        if (vm.conditions.orderEndTime) {
          url = url + "end=" + vm.conditions.orderEndTime + "&";
        }
      }*/
      if (this.selectedChannel == 0){
        this.selectedChannel = null;
      }
      let param = {page:1}
      vm.conditions.storeId ? Object.assign(param,{stores:[vm.conditions.storeId]}):''
      /*vm.conditions.orderStartTime ? Object.assign(param,{begin:vm.conditions.orderStartTime}):''
      vm.conditions.orderEndTime ? Object.assign(param,{end:vm.conditions.orderEndTime}):''*/
      this.orderTime && this.orderTime.length > 0 ? Object.assign(param,{begin:this.orderTime[0]}):'';
      this.orderTime && this.orderTime.length > 0 ? Object.assign(param,{end:this.orderTime[1]}):'';
      this.conditions.status ?  Object.assign(param,{status:this.conditions.status}):'';
      this.select == '1' ? Object.assign(param,{platformOrderId:this.selectInputValue}):'';
      this.select == '2' ? Object.assign(param,{record:this.selectInputValue}):'';
      this.select == '3' ? Object.assign(param,{sku:this.selectInputValue}):'';
      this.select == '4' ? Object.assign(param,{erpSku:this.selectInputValue}):'';
      this.select == '5' ? Object.assign(param,{receiver:this.selectInputValue}):'';
      this.select == '6' ? Object.assign(param,{buyerId:this.selectInputValue}):'';
      this.selectedChannel ?  Object.assign(param,{channel:this.selectedChannel}):'';
      instance({
        method: 'post',
        url: url,
        data:param
      }).then(function (data) {
        if (data.data.success) {
          vm.channelCount.set("All", data.data.data.All);
          vm.channelCount.set("UnConfirmed", data.data.data.UnConfirmed);
          vm.channelCount.set("PendingDeliver", data.data.data.PendingDeliver);
          vm.channelCount.set("Prepare", data.data.data.Prepare);
          vm.channelCount.set("Deliver", data.data.data.Deliver);
          vm.channelCount.set("Canceled", data.data.data.Canceled);
          if (vm.selectedChannel == null){
            vm.selectedChannel = 0;
          }
        } else {
          vm.alertMessage(false);
        }
      })
    },
    //根据状态筛选
    createOrderStatusCondition: function (_statusValue, index) {
      let vm = this;
      vm.countOrderClass = index;
      vm.conditions.status = _statusValue;
      vm.getOrderList();


    },
    handleSearch(){
      this.currentPage = 1;
      this.getChannelCount();
      this.getOrderList()
    },
    //获取订单列表
    getOrderList: function () {
      let vm = this;
      let ttt = `/v1/order/list`;
    /*  if (vm.conditions.status != 0) {  ?page=${vm.currentPage}&channel=${vm.selectedChannel}&
        ttt = ttt + "status=" + vm.conditions.status + "&";
      }
      if (vm.conditions.storeId) {
        ttt = ttt + "storeId=" + vm.conditions.storeId + "&";
      }*/
    if (this.selectedChannel == 0){
      this.selectedChannel = null;
    }
      let param = {page:this.currentPage};
      this.conditions.status ?  Object.assign(param,{status:this.conditions.status}):'';
      this.select == '1' ? Object.assign(param,{platformOrderId:this.selectInputValue}):'';
      this.select == '2' ? Object.assign(param,{record:this.selectInputValue}):'';
      this.select == '3' ? Object.assign(param,{sku:this.selectInputValue}):'';
      this.select == '4' ? Object.assign(param,{erpSku:this.selectInputValue}):'';
      this.select == '5' ? Object.assign(param,{receiver:this.selectInputValue}):'';
      this.select == '6' ? Object.assign(param,{buyerId:this.selectInputValue}):'';
      this.conditions.storeId ? Object.assign(param,{stores:[this.conditions.storeId]}):'';
      this.orderTime && this.orderTime.length > 0 ? Object.assign(param,{begin:this.orderTime[0]}):'';
      this.orderTime && this.orderTime.length > 0 ? Object.assign(param,{end:this.orderTime[1]}):'';
      this.selectedChannel ?  Object.assign(param,{channel:this.selectedChannel}):'';

      instance({
        method: 'post',
        url: ttt,
        data:param,
      }).then(function (data) {
        if (data.data.success) {
          if(!data.data.data){
            vm.orderList = [];
          }else {
            vm.orderList = data.data.data.list;
            console.log('hdakshdkas',vm.orderList)
          }
          vm.pages.total = data.data.data.pages
          vm.pages.current = data.data.data.pageNum;
          vm.totalNumPage =  data.data.data.total;
          if (vm.selectedChannel == null){
            vm.selectedChannel = 0;
          }
          console.log()
        } else {
          vm.alertMessage(false);
        }
      })
    },
    //根据商品数量和单价计算订单金额
    countTotalPrice: function (_index) {
      let vm = this;
      let count = 0;
      vm.orderDetail.items.forEach(function (item, index) {
        count = count + item.price * item.quantity;
        if (_index == index) {
          let i = item.wareHouseOptions.findIndex(function (wareHouse) {
            return wareHouse.whId == item.stockId;
          });
          if (item.wareHouseOptions[i].stockQty < item.quantity) {
            vm.$message({
              showClose: false,
              message: '请调整发货数量!',
              type: 'warning'
            });
            item.quantity = '';
            vm.$set(vm.orderDetail.items, index, item);
          }
        }
      });
      vm.orderDetail.total = count;
    },
    //计算库位数量不足不让选择此库位
    getStockQuetity: function (id, index) {
      let vm = this;
      let wareHouses = vm.orderDetail.items[index].wareHouseOptions;
      let i = wareHouses.findIndex(function (wareHouse) {
        return wareHouse.whId == id;
      });
      let item1 = vm.orderDetail.items[i];
      if (wareHouses[i].stockQty < item1.quantity) {
        vm.$message({
          showClose: false,
          message: '请重新选择发货仓库!',
          type: 'warning'
        });
        item1.stockId = '';
        vm.$set(vm.orderDetail.items, index, item1);
      }
    },
    //添加库存商品 页面添加
    addStockGoods: function (index) {
      let vm = this;
      let itemTem = Object.assign({}, vm.orderDetail.items[index]);
      itemTem.factSku = '';
      itemTem.factTitle = '';
      itemTem.wareHouseOptions = [];
      vm.orderDetail.items.splice(vm.orderDetail.items.length + 1, 1, itemTem);
    },
    //删除订单明细商品 页面删除
    deleteStockGoods: function (index) {
      let vm = this;
      if (index == 0) {
        return;
      }
      vm.orderDetail.items.splice(index, 1);
    },
    //添加产品
    addProduct: function (index) {
      let vm = this;
      vm.replaceIndex = index;
      vm.checkedProduct = [];
      instance.post('/v1/warehouse/getStockList', {
        "sku": vm.sku,
        "rows": vm.inventory.dispaly,
        "page": vm.inventory.pageNum,
      }).then(function (data) {
        vm.addProductList = data.data.data.list;
        vm.inventory.total = data.data.data.total;
        vm.inventory.pageNum = data.data.data.pageNum;
      })
    },
    //替换原订单中的商品
    replaceGoods: function (index) {
      let vm = this;
      vm.itemTem = {};
      //index 是更换商品的下标
      if (index == null) {
        if (!vm.checkedProduct) {
          vm.$alert('请添加出库商品！', '提示', {
            confirmButtonText: '确定',
          });
          return;
        } else if (vm.checkedProduct.length > 1) {
          vm.$alert('请选择一个商品！', '提示', {
            confirmButtonText: '确定',
          });
          return;
        } else {
          index = vm.checkedProduct[0];
        }
      }
      let goodsItem = vm.addProductList[index]; //选中的更换商品
      //被替换订单明细商品
      //只替换sku商品名称和仓库
      vm.orderDetail.items[vm.replaceIndex].factSku = goodsItem.sku;
      vm.orderDetail.items[vm.replaceIndex].stockId = goodsItem.whId;
      vm.orderDetail.items[vm.replaceIndex].goodsId = goodsItem.id;
      vm.orderDetail.items[vm.replaceIndex].factTitle = goodsItem.goodsName;
      vm.orderDetail.items[vm.replaceIndex].factBrand = goodsItem.brandName;
      vm.orderDetail.items[vm.replaceIndex].factImage = goodsItem.goodsPic;
      if (!goodsItem.countStock && goodsItem.countStock != 0) {
        vm.$alert('请去维护商品库存！', '提示', {
          confirmButtonText: '确定',
        });
        return;
      }
      vm.orderDetail.items[vm.replaceIndex].wareHouseOptions.splice(0);
      vm.itemTem = Object.assign({}, vm.orderDetail.items[vm.replaceIndex]);
      let wareHouseMap = new Map();
      let wareHouseMapValue = {};
      instance.post('/v1/warehouse/getGoodsStockInfoList', {
        "sku": goodsItem.sku,
      }).then(function (data) {
        let stockVos = data.data.data[0].stockInfoVOS;
        for (let i = 0; i < stockVos.length; i++) {
          //将仓库ID作为key值，存入map中
          if (wareHouseMap.has(stockVos[i].whId)) {
            //先判断有没有此仓库ID，如果有，则做库存累加；
            wareHouseMapValue = wareHouseMap.get(stockVos[i].whId);
            wareHouseMapValue.stockQty = parseInt(wareHouseMapValue.stockQty) + parseInt(stockVos[i].stockQty);
            wareHouseMap.set(stockVos[i].whId, wareHouseMapValue);
          } else {
            let currentWareHouseMapValue = {};
            currentWareHouseMapValue.whName = stockVos[i].whName;
            currentWareHouseMapValue.stockQty = stockVos[i].stockQty;
            currentWareHouseMapValue.goodsId = stockVos.goodsId;
            wareHouseMap.set(stockVos[i].whId, currentWareHouseMapValue);
          }
        }
        vm.orderDetail.items[vm.replaceIndex].wareHouseOptions = [];
        let currentItem = vm.orderDetail.items[vm.replaceIndex];
        wareHouseMap.forEach((value, key) => {
          let wareHouseOption = {};
          wareHouseOption.whId = key;
          wareHouseOption.whName = value.whName;
          wareHouseOption.stockQty = value.stockQty;
          currentItem.goodsId = value.goodsId;
          currentItem.wareHouseOptions.push(wareHouseOption);
        });
        vm.$set(vm.orderDetail.items,vm.replaceIndex, currentItem);
      });
      vm.clearParam();
      $("#modal-addGoods").modal('hide');
    },
    returnPlatformStatus: function (_key) {
      return this.platformStatus.get(_key);
    },
    returnOrderStatus: function (_key) {
      return this.orderStatus.get(_key);
    },
    returnOrderType: function (_key) {
      return this.orderType.get(_key);
    },
    returnChannelCount: function (_key) {
      return this.channelCount.get(_key);
    },
    //获取退补类型
    getRetreatingType: function () {
      let vm = this;
      instance.get('/v1/dict/charge').then(function (data) {
        vm.retreatingType = data.data.data;
      })
    },
    //同步订单
    getOrderByHander: function () {
      let vm = this;
      if (!vm.conditions.orderStartTime) {
        vm.$alert('请选择订单开始时间！', '提示', {
          confirmButtonText: '确定',
        });
        return;
      }
      if (!vm.conditions.orderEndTime) {
        vm.$alert('请选择订单结束时间！', '提示', {
          confirmButtonText: '确定',
        });
        return;
      }
      let param = {
        storeId:vm.conditions.storeId,
        begin:vm.conditions.orderStartTime,
        end:vm.conditions.orderEndTime
      };
      instance.post('/v1/order/' + vm.selectedChannel + '/pull?',param).then(function (data) {
        vm.retreatingType = data.data.data;
        vm.alertMessage(data.data.success);
        vm.getOrderList();
      })
    },
    //获取店铺名字
    getStoreNameById: function (id) {
      let vm = this;
      for (let i = 0; i < vm.shopListBtn.length; i++) {
        if (vm.shopListBtn[i].id == id) {
          return vm.shopListBtn[i].name;
        }
      }
    },
    //导出到U8
    u8OrderDownload: function () {
      let vm = this;
      let param = {};
      if (!vm.conditions.orderStartTime) {
        vm.$alert('请选择订单开始时间！', '提示', {
          confirmButtonText: '确定',
        });
        return;
      }
      if (!vm.conditions.orderEndTime) {
        vm.$alert('请选择订单结束时间！', '提示', {
          confirmButtonText: '确定',
        });
        return;
      }
      param.channel = vm.selectedChannel;
      param.begin = vm.conditions.orderStartTime;
      param.end = vm.conditions.orderEndTime;
      param.orderId = vm.conditions.orderId;
      instance({
        method: 'post',
        url: '/v1/order/export/u8',
        data: param,
        responseType: 'blob'
      }).then(function (data) {
        console.log(data)
        if (!data.data) {
          vm.$alert('下载失败！', '提示', {
            confirmButtonText: '确定',
          });
        } else {
          vm.download(data);
        }
      });
    },
    // 下载文件
    download(data) {
      if (!data) {
        vm.$alert('下载失败！', '提示', {
          confirmButtonText: '确定',
        });
        return;
      }
      if (window.navigator.msSaveBlob) {
        // for ie 10 and later
        try {
          let blob = new Blob([data.data], {type: "application/vnd.ms-excel"});
          // let blob = new Blob([data.data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
          window.navigator.msSaveBlob(blob, 'u8订单.xlsx');
        }
        catch (e) {
          console.log(e);
        }
      } else {
        let blob = new Blob([data.data], {type: "application/vnd.ms-excel"});
        // let blob = new Blob([data.data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
        let url = URL.createObjectURL(blob);
        let link = document.createElement('a');
        link.style.display = 'none';
        link.href = url;
        link.setAttribute('download', 'u8订单');
        document.body.appendChild(link);
        link.click();
        URL.revokeObjectURL(url);
      }
    },
    //初始化页面基础数据
    initBasicData: function () {
      //初始化订单状态
      this.orderStatus.set(1, "待确认");
      this.orderStatus.set(2, "待发货");
      this.orderStatus.set(3, "配货中");
      this.orderStatus.set(4, "已取消");
      this.orderStatus.set(5, "已发货");
      this.orderType.set(0, "非9610报关单模式");
      this.orderType.set(1, "9610模式");
      this.orderType.set(2, "非9610物流单模式");
      let date  = new Date();
      let day = new Date(date-15*24*3600*1000);
      //格式化赋值
      this.conditions.orderStartTime = '';
      this.conditions.orderEndTime = '';
      // this.conditions.orderStartTime = day.getFullYear() + '-' + (day.getMonth() + 1) + '-' + day.getDate() + ' 00:00:00';
      // this.conditions.orderEndTime = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' 00:00:00';
      //初始化平台状态
      this.platformStatus.set(1, "支付未完成");
      this.platformStatus.set(2, "支付完成");
    },
    //初始化页面动态数据
    initPageData: function () {
      this.getOrderList();
      this.getRetreatingType();
    },

    print: function() {
      let str = `<style>h3{font-weight: bold;} div{width: 50%; float: left;} .full-row{width: 100%} div > label:nth-child(1){font-weight: bold;}</style>`;
      let $div = $("#modal-order-confirm .for-print").clone().prepend(str);
      print($div[0]);
    },

    getWarehouse(wareHouseOptions, stockId) {
      /**
       * <select @click="getStockQuetity(orderItem.stockId,itemIndex)" class="form-control"
                        :disabled="!showFlag" v-model="orderItem.stockId">
                  <div>
                    <span
                      v-for="wareHouseOption in orderItem.wareHouseOptions">{{wareHouseOption.whName}}</span>
                  </div>
                  <option :value="wareHouseOption.whId"
                          v-for="wareHouseOption in orderItem.wareHouseOptions">
                    {{wareHouseOption.whName}}({{wareHouseOption.stockQty}})
                  </option>
                </select>
       */
      if(wareHouseOptions && wareHouseOptions.length) {
        let temp = wareHouseOptions.filter((r)=>{
          return r.whId == stockId;
        })[0];
        return temp && (temp.whName + "("+temp.stockQty+")") || "";
      }

      return "";
    },
    submitUpload() {
      let vm = this;
      vm.$confirm('此操作将导入订单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        vm.importUrl = '/api/v1/common/order/import/' + vm.orderForm.orderType
        setTimeout(function () {
          vm.$refs.upload.submit();
        }, 400)
      }).catch(() => {

      })
    },
    /*选择导入导出跳转*/
    handleChoseClick(command){
      if (command == 1){
        this.handleGetDownM();
      }else if (command == 2){
        this.dialogVisibleChose= true
      }else if(command == 3){
        this.orderOut()
      }
      console.log('djsak')
    },
    /*同步选择*/
    handleSynchronizationClick(command){
      if (command == 1){
        this.dialogVisibleSynchronous= true
      }else if (command == 2){
        this.$router.push('/v1/order/log/list')
      }
      console.log('89080980')
    },
    handleCreatOrder(){
      this.$router.push('/v1/order/create')
    },
    /*获取时间区间*/
    handleGetTime(){
      if (this.orderTime) {
        this.conditions.orderStartTime = this.orderTime[0];
        this.conditions.orderEndTime = this.orderTime[1];
      }
    },
    handleGetDownM(){
      let url = baseURL+'/v1/common/order/download';
      let link = document.createElement('a');
      link.style.display = 'none';
      link.href = url;
      link.setAttribute('download', '订单导入模版');
      document.body.appendChild(link);
      link.click();
 /*     instance({
        method: 'post',
        url: '/v1/common/order/download',
      }).then( (data)=> {
         /!* window.open(data.data)*!/
        console.log(data)
        this.downloadFile(data,'订单导入模版')
      })*/
    },
    // 下载文件
    downloadFile(data,name) {
      if (!data) {
        vm.$alert('下载失败！', '提示', {
          confirmButtonText: '确定',
        });
        return;
      }
      if (window.navigator.msSaveBlob) {
        // for ie 10 and later
        try {
         /* let blob = new Blob([data.data], {type: "application/vnd.ms-excel"});*/
          let blob = new Blob([data.data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
          window.navigator.msSaveBlob(blob, `${name}.xlsx`);
        }
        catch (e) {
          console.log(e);
        }
      } else {
       /* let blob = new Blob([data.data], {type: "application/vnd.ms-excel"});*/
         let blob = new Blob([data.data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
        let url = URL.createObjectURL(blob);
        let link = document.createElement('a');
        link.style.display = 'none';
        link.href = url;
        link.setAttribute('download', `${name}`);
        document.body.appendChild(link);
        link.click();
        URL.revokeObjectURL(url);
      }
    },
    handleGetType(command){

    },
    /*获取9610列表*/
    getPopNine(){
      let param  = {channel:this.searchPopChannel,stores:[this.searchPopShop]}
      this.searchPopTimeList.length > 1 ? Object.assign(param,{begin:this.searchPopTimeList[0],end:this.searchPopTimeList[1]}):'';
      instance({
        method: 'post',
        url: '/v1/order/9610/list',
        data:param,
      }).then( (data)=> {
        let result = data.data.data;
          this.searchPopTableList = result;
          this.showTableList =  this.searchPopTableList.slice((this.popCurrentPage-1)*10,this.popCurrentPage*10);
          this.popTotalCount = result.length;

      })
    },
    popCurrentPageSearch(){
      this.popCurrentPage = 1;
      this.getPopNine();
    },
    /*获取9610店铺*/
    popPlatformChannels() {
      let vm = this;
      if ( vm.selectedChannel == 0){
        vm.selectedChannel = null;
      }
      vm.searchPopShop = '';
      vm.searchPopshopListBtn = [];
      vm.searchPopshopListBtn.push({id:null,name:'全部'})
      instance({
        method: 'post',
        url: 'v1/author/getAuthorShopList',
        data: {
          id: vm.searchPopChannel
        }
      }).then(function (data) {
        if (data.data.success) {
          let result = data.data.data;
          vm.searchPopshopListBtn = vm.searchPopshopListBtn.concat(result);
          if ( vm.selectedChannel == null){
            vm.selectedChannel = 0;
          }
        }
      })
    },
    /*9610列表分页*/
    popPageChange(pageIndex){
      this.popCurrentPage = pageIndex;
      this.popTotalCount =  this.searchPopTableList.length;
      this.showTableList = this.searchPopTableList.slice((pageIndex - 1)*10,pageIndex*10);
    },
    /*9610删除数据处理*/
    handleClickDelet(id){
      this.searchPopTableList.forEach((item,index)=>{
         if (item.id == id) {
           this.searchPopTableList.splice(index,1);
           this.popPageChange(this.popCurrentPage);
         }
      })
    },
    /*订单编号搜索*/
    handleSearchPlatformOrderId(){
      this.showTableList = []
      this.searchPopTableList.forEach((item,index)=>{
         if (item.platformOrderId == this.searchPopPlatformOrderId){
           this.showTableList.push(item);
           this.popTotalCount = 1;
           this.popCurrentPage = 1;
         }
      })
    },
    /*处理剩余9610数据组装id*/
    handleDealData(){
      let idList = [];
      this.searchPopTableList.forEach((item,index)=>{
        idList.push(item.platformOrderId)
      });
      return idList
    },
    /*标记9610提交*/
    popOutSubmit(){
      if (!this.customsNo){
        this.$alert('请输入申报关区代码！', '提示', {
          confirmButtonText: '确定',
        });
        return
      }
      if (this.handleDealData().length == 0){
        this.$alert('请选择需要标记的订单！', '提示', {
          confirmButtonText: '确定',
        });
        return
      }
       let param = {customsNo:this.customsNo,orderIds:this.handleDealData(),orderType:1};
      instance({
        method: 'post',
        url: '/v1/order/9610/tag',
        data:param,
      }).then( (data)=> {
         this.$message.success('标记成功');
         this.innerVisible = false;
         this.dialogVisible = false;
         this.searchPopChannel = null;
         this.popPlatformChannels();
      })
    },
    /*订单上传获取店铺*/
    popSynchronousChannels() {
      let vm = this;
      if ( vm.synchronousChannel == 0){
        vm.synchronousChannel = null;
      }
      vm.synchronousshopListBtn = [];
      vm.synchronousshopListBtn.push({id:null,name:'全部'})
      instance({
        method: 'post',
        url: 'v1/author/getAuthorShopList',
        data: {
          id: vm.synchronousChannel
        }
      }).then(function (data) {
        if (data.data.success) {
          let result = data.data.data;
          vm.synchronousshopListBtn = vm.synchronousshopListBtn.concat(result);
          if (vm.synchronousChannel == null){
            vm.synchronousChannel = 0
          }
        }
      })
    },
    /*订单上传*/
    orderUpload(){
      if (this.synchronousChannel == null){
        this.$alert('请选择平台！', '提示', {
          confirmButtonText: '确定',
        });
        return
      }
      if (this.synchronousshopValue == ''){
        this.$alert('请选择店铺！', '提示', {
          confirmButtonText: '确定',
        });
        return
      }
      let api = `/v1/order/${this.synchronousChannel}/pull`;
      let param = {storeId:this.synchronousshopValue.toString()};
      this.synchronousTimeList.length > 0 ?  Object.assign(param,{begin:this.synchronousTimeList[0],end:this.synchronousTimeList[1]}):'';
      instance({
        method: 'post',
        url: api,
        data: param
      }).then( (data)=> {
        if (data.data.success) {
          let result = data.data.data;
          this.synchronousshopValue = ''
          this.synchronousshopListBtn = [];
          this.synchronousChannel = null;
          this.synchronousTimeList = [];
          this.dialogVisibleSynchronous = false;
          this.$alert('订单正在同步中，请10分钟后，查看同步订单！', '提示', {
            confirmButtonText: '确定',
          });
        }else {
          this.$alert(data.data.msg, '提示', {
            confirmButtonText: '确定',
          });
        }
      })
    },
    handleChoseChannel(flag){
      switch (flag) {
        case 1:
          return 'ebay';
          break;
        case 2:
          return 'Amazon';
          break;
        case 3:
          return 'magento';
          break;
        case 4:
          return '其他';
          break;
        default:
          return '其他'
          break;
      }
    },
    viewOrderDdit(id){
       this.$router.push(`/v1/order/create?orderId=${id}`)
    },
    toMoney(num){
      if(num){
        if(isNaN(num)) {
          alert("金额中含有不能识别的字符");
          return;
        }
        num = typeof num == "string"?parseFloat(num):num//判断是否是字符串如果是字符串转成数字
        num = num.toFixed(2);//保留两位
        num = parseFloat(num);//转成数字
        num = num.toLocaleString();//转成金额显示模式
        //判断是否有小数
        if(num.indexOf(".")==-1){
          num = num+".00";
        }else{
          num = num.split(".")[1].length<2? num+"0": num;
        }
        return num;//返回的是字符串23,245.12保留2位小数
      }else{
        return num = null;
      }
    },
    handleDialogVisible(){
      this.dialogVisible = true;
     /* this.platformChannelsBtns = null*/
      this.searchPopshopListBtn =null;
      this.searchPopTimeList = [];
      this.searchPopPlatformOrderId = '';
      this.searchPopChannel = '';
      this.searchPopShop = '';
      this.showTableList = [];
      this.popCurrentPage = 1;
      this.popTotalCount = 0;
    },
    /*订单导出*/
    orderOut(){
      if (this.selectedChannel == 0){
        this.selectedChannel = null;
      }
      let param = {page:1}
      this.conditions.storeId ? Object.assign(param,{stores:[this.conditions.storeId]}):''
      this.orderTime && this.orderTime.length > 0 ? Object.assign(param,{begin:this.orderTime[0]}):'';
      this.orderTime && this.orderTime.length > 0 ? Object.assign(param,{end:this.orderTime[1]}):'';
      this.conditions.status ?  Object.assign(param,{status:this.conditions.status}):'';
      this.select == '1' ? Object.assign(param,{platformOrderId:this.selectInputValue}):'';
      this.select == '2' ? Object.assign(param,{record:this.selectInputValue}):'';
      this.select == '3' ? Object.assign(param,{sku:this.selectInputValue}):'';
      this.select == '4' ? Object.assign(param,{erpSku:this.selectInputValue}):'';
      this.select == '5' ? Object.assign(param,{receiver:this.selectInputValue}):'';
      this.select == '6' ? Object.assign(param,{buyerId:this.selectInputValue}):'';
      this.selectedChannel ?  Object.assign(param,{channel:this.selectedChannel}):'';
      let api = '/v1/common/order/export'
      instance({
        method: 'post',
        url: api,
        data: param,
        responseType: 'blob'
      }).then( (data)=> {
        if (this.selectedChannel == null){
          this.selectedChannel = 0;
        }
          this.downloadFile(data,'订单')
      })
    },
    getLogistics(){
      let api = '/v1/dict/logistics';
      instance({
        method:'get',
        url:api
      }).then((res)=>{
        if (res.data.success){
          this.logisticsListA = res.data.data
        }
      })
    },

  },
  created() {
    this.getShopList();
    this.initBasicData();
    this.initPageData();
    this.getPlatform();
    this.getLogistics();
    this.getCountryOptions();
    this.getChannelCount();
  },
  computed: {
    retreatingTypeStr() {
      /**
       * <select class="form-control" :disabled="!showFlag" v-model="orderDetail.treatType">
                              <option :value="type.code" v-for="type in retreatingType">{{type.codeValue}}</option>
                            </select>
       */
      if(this.retreatingType && this.retreatingType.length) {
        let temp = this.retreatingType.filter((r)=>{
          return r.code == this.orderDetail.treatType;
        })[0];
        return temp && temp.codeValue || "";
      }

      return "";
    },

    countryName() {
      /**
       * <select name="" class="form-control" v-model="orderDetail.country"
                                        :disabled="!showFlag">
                                  <option v-for="country in countryOptions" :value="country.code">{{country.name}}
                                  </option>
                                </select>
       */
      if(this.countryOptions && this.countryOptions.length) {
        let temp = this.countryOptions.filter((r)=>{
          return r.code == this.orderDetail.country;
        })[0];
        return temp && temp.name || "";
      }

      return "";
    }
  },
}
